{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Torch Hub Inference Tutorial\n",
    "\n",
    "In this tutorial you'll learn:\n",
    "- how to load a pretrained model using Torch Hub \n",
    "- run inference to classify the action in a demo video"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Install and Import modules"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "If `torch`, `torchvision` and `pytorchvideo` are not installed, run the following cell:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "try:\n",
    "    import torch\n",
    "except ModuleNotFoundError:\n",
    "    !pip install torch torchvision\n",
    "    import os\n",
    "    import sys\n",
    "    import torch\n",
    "    \n",
    "if torch.__version__=='1.6.0+cu101' and sys.platform.startswith('linux'):\n",
    "    !pip install pytorchvideo\n",
    "else:\n",
    "    need_pytorchvideo=False\n",
    "    try:\n",
    "        # Running notebook locally\n",
    "        import pytorchvideo\n",
    "    except ModuleNotFoundError:\n",
    "        need_pytorchvideo=True\n",
    "    if need_pytorchvideo:\n",
    "        # Install from GitHub\n",
    "        !pip install \"git+https://github.com/facebookresearch/pytorchvideo.git\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json \n",
    "from torchvision.transforms import Compose, Lambda\n",
    "from torchvision.transforms._transforms_video import (\n",
    "    CenterCropVideo,\n",
    "    NormalizeVideo,\n",
    ")\n",
    "from pytorchvideo.data.encoded_video import EncodedVideo\n",
    "from pytorchvideo.transforms import (\n",
    "    ApplyTransformToKey,\n",
    "    ShortSideScale,\n",
    "    UniformTemporalSubsample,\n",
    "    UniformCropVideo\n",
    ") \n",
    "from typing import Dict"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Setup \n",
    "\n",
    "Download the id to label mapping for the Kinetics 400 dataset on which the Torch Hub models were trained. \n",
    "This will be used to get the category label names from the predicted class ids."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "!wget https://dl.fbaipublicfiles.com/pyslowfast/dataset/class_names/kinetics_classnames.json "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open(\"kinetics_classnames.json\", \"r\") as f:\n",
    "    kinetics_classnames = json.load(f)\n",
    "\n",
    "# Create an id to label name mapping\n",
    "kinetics_id_to_classname = {}\n",
    "for k, v in kinetics_classnames.items():\n",
    "    kinetics_id_to_classname[v] = str(k).replace('\"', \"\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load Model using Torch Hub API\n",
    "\n",
    "PyTorchVideo provides several pretrained models through Torch Hub. Available models are described in [model zoo documentation](https://github.com/facebookresearch/pytorchvideo/blob/main/docs/source/model_zoo.md#kinetics-400). \n",
    "\n",
    "Here we are selecting the `slowfast_r50` model which was trained using a 8x8 setting on the Kinetics 400 dataset. \n",
    "\n",
    "\n",
    "NOTE: to run on GPU in Google Colab, in the menu bar selet: Runtime -> Change runtime type -> Harware Accelerator -> GPU\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Device on which to run the model\n",
    "# Set to cuda to load on GPU\n",
    "device = \"cpu\"\n",
    "\n",
    "# Pick a pretrained model \n",
    "model_name = \"slowfast_r50\"\n",
    "model = torch.hub.load(\"facebookresearch/pytorchvideo:main\", model=model_name, pretrained=True)\n",
    "\n",
    "# Set to eval mode and move to desired device\n",
    "model = model.to(device)\n",
    "model = model.eval()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Define the transformations for the input required by the model\n",
    "\n",
    "Before passing the video into the model we need to apply some input transforms and sample a clip of the correct duration.\n",
    "\n",
    "NOTE: The input transforms are specific to the model. If you choose a different model than the example in this tutorial, please refer to the code provided in the Torch Hub documentation and copy over the relevant transforms:\n",
    "- [SlowFast](https://pytorch.org/hub/facebookresearch_pytorchvideo_slowfast/)\n",
    "- [X3D](https://pytorch.org/hub/facebookresearch_pytorchvideo_x3d/)\n",
    "- [Slow](https://pytorch.org/hub/facebookresearch_pytorchvideo_resnet/)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "####################\n",
    "# SlowFast transform\n",
    "####################\n",
    "\n",
    "side_size = 256\n",
    "mean = [0.45, 0.45, 0.45]\n",
    "std = [0.225, 0.225, 0.225]\n",
    "crop_size = 256\n",
    "num_frames = 32\n",
    "sampling_rate = 2\n",
    "frames_per_second = 30\n",
    "alpha = 4\n",
    "\n",
    "class PackPathway(torch.nn.Module):\n",
    "    \"\"\"\n",
    "    Transform for converting video frames as a list of tensors. \n",
    "    \"\"\"\n",
    "    def __init__(self):\n",
    "        super().__init__()\n",
    "        \n",
    "    def forward(self, frames: torch.Tensor):\n",
    "        fast_pathway = frames\n",
    "        # Perform temporal sampling from the fast pathway.\n",
    "        slow_pathway = torch.index_select(\n",
    "            frames,\n",
    "            1,\n",
    "            torch.linspace(\n",
    "                0, frames.shape[1] - 1, frames.shape[1] // alpha\n",
    "            ).long(),\n",
    "        )\n",
    "        frame_list = [slow_pathway, fast_pathway]\n",
    "        return frame_list\n",
    "\n",
    "transform =  ApplyTransformToKey(\n",
    "    key=\"video\",\n",
    "    transform=Compose(\n",
    "        [\n",
    "            UniformTemporalSubsample(num_frames),\n",
    "            Lambda(lambda x: x/255.0),\n",
    "            NormalizeVideo(mean, std),\n",
    "            ShortSideScale(\n",
    "                size=side_size\n",
    "            ),\n",
    "            CenterCropVideo(crop_size),\n",
    "            PackPathway()\n",
    "        ]\n",
    "    ),\n",
    ")\n",
    "\n",
    "# The duration of the input clip is also specific to the model.\n",
    "clip_duration = (num_frames * sampling_rate)/frames_per_second"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load an example video\n",
    "We can test the classification of an example video from the kinetics validation set such as this [archery video](https://www.youtube.com/watch?v=3and4vWkW4s)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Download the example video file\n",
    "!wget https://dl.fbaipublicfiles.com/pytorchvideo/projects/archery.mp4 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Load the example video\n",
    "video_path = \"archery.mp4\"  \n",
    "\n",
    "# Select the duration of the clip to load by specifying the start and end duration\n",
    "# The start_sec should correspond to where the action occurs in the video\n",
    "start_sec = 0\n",
    "end_sec = start_sec + clip_duration \n",
    "\n",
    "# Initialize an EncodedVideo helper class\n",
    "video = EncodedVideo.from_path(video_path)\n",
    "\n",
    "# Load the desired clip\n",
    "video_data = video.get_clip(start_sec=start_sec, end_sec=end_sec)\n",
    "\n",
    "# Apply a transform to normalize the video input\n",
    "video_data = transform(video_data)\n",
    "\n",
    "# Move the inputs to the desired device\n",
    "inputs = video_data[\"video\"]\n",
    "inputs = [i.to(device)[None, ...] for i in inputs]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Get model predictions"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Pass the input clip through the model \n",
    "preds = model(inputs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Get the predicted classes \n",
    "post_act = torch.nn.Softmax(dim=1)\n",
    "preds = post_act(preds)\n",
    "pred_classes = preds.topk(k=5).indices\n",
    "\n",
    "# Map the predicted classes to the label names\n",
    "pred_class_names = [kinetics_id_to_classname[int(i)] for i in pred_classes[0]]\n",
    "print(\"Predicted labels: %s\" % \", \".join(pred_class_names))"
   ]
  }
 ],
 "metadata": {
  "bento_stylesheets": {
   "bento/extensions/flow/main.css": true,
   "bento/extensions/kernel_selector/main.css": true,
   "bento/extensions/kernel_ui/main.css": true,
   "bento/extensions/new_kernel/main.css": true,
   "bento/extensions/system_usage/main.css": true,
   "bento/extensions/theme/main.css": true
  },
  "kernelspec": {
   "display_name": "pytorchvideo_etc (local)",
   "language": "python",
   "name": "pytorchvideo_etc_local"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
